package com.yu.gulimall.product.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yu.common.utils.PageUtils;
import com.yu.common.utils.Query;
import com.yu.gulimall.product.dao.AttrAttrgroupRelationDao;
import com.yu.gulimall.product.dao.AttrDao;
import com.yu.gulimall.product.dao.AttrGroupDao;
import com.yu.gulimall.product.dao.CategoryDao;
import com.yu.gulimall.product.entity.AttrAttrgroupRelationEntity;
import com.yu.gulimall.product.entity.AttrEntity;
import com.yu.gulimall.product.entity.AttrGroupEntity;
import com.yu.gulimall.product.entity.CategoryEntity;
import com.yu.gulimall.product.service.AttrService;
import com.yu.gulimall.product.vo.AttrEntityVo;
import com.yu.gulimall.product.vo.AttrInfoVo;
import com.yu.gulimall.product.vo.AttrVo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {

    @Resource
    private CategoryDao categoryDao;

    @Resource
    private AttrAttrgroupRelationDao attrAttrgroupRelationDao;

    @Resource
    private AttrGroupDao attrGroupDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils getBaseAttrWithCatelogName(Map<String, Object> params, Long catelogId, String type) {
        String key = (String) params.get("key");
        QueryWrapper<AttrEntity> attrEntityQueryWrapper = new QueryWrapper<>();
        attrEntityQueryWrapper.eq("attr_type", "base".equalsIgnoreCase(type) ? 1 : 0);
        if (catelogId != 0) {
            attrEntityQueryWrapper.eq("catelog_id", catelogId);
        }
        if (StrUtil.isNotBlank(key)) {
            // 关键字不为空的情况
            attrEntityQueryWrapper.and((item) -> {
                item.eq("attr_id", key).or().like("attr_name", key);
            });
        }
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                attrEntityQueryWrapper
        );
        List<AttrEntity> records = page.getRecords();
        List<AttrEntityVo> collect = records.stream().map((item) -> {
            AttrEntityVo attrEntityVo = new AttrEntityVo();
            BeanUtil.copyProperties(item, attrEntityVo);
            Long catelogId1 = item.getCatelogId();
            CategoryEntity categoryEntity = categoryDao.selectOne(new QueryWrapper<CategoryEntity>().eq("cat_id", catelogId1));
            attrEntityVo.setCatelogName(categoryEntity.getName());
            Long attrId = item.getAttrId();
            if (attrEntityVo.getAttrType()==1) {
                AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = attrAttrgroupRelationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrId));
                if(attrAttrgroupRelationEntity!=null){
                    Long attrGroupId = attrAttrgroupRelationEntity.getAttrGroupId();
                    AttrGroupEntity attrGroupEntity = attrGroupDao.selectOne(new QueryWrapper<AttrGroupEntity>().eq("attr_group_id", attrGroupId));
                    attrEntityVo.setGroupName(attrGroupEntity.getAttrGroupName());
                }else {
                    attrEntityVo.setGroupName(null);
                }
            }
            return attrEntityVo;
        }).collect(Collectors.toList());
        Page<AttrEntityVo> attrEntityVoPage = new Page<>();
        BeanUtil.copyProperties(page, attrEntityVoPage, "records");
        attrEntityVoPage.setRecords(collect);
        return new PageUtils(attrEntityVoPage);
    }


    @Transactional
    @Override
    public void saveDetail(AttrVo attr) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtil.copyProperties(attr, attrEntity);
        // 保存基本数据
        this.save(attrEntity);
        // 保存关联关系
        if(attr.getAttrType()==1){
            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = new AttrAttrgroupRelationEntity();
            attrAttrgroupRelationEntity.setAttrGroupId(attr.getAttrGroupId());
            attrAttrgroupRelationEntity.setAttrId(attrEntity.getAttrId());
            attrAttrgroupRelationDao.insert(attrAttrgroupRelationEntity);
        }
    }

    @Override
    public AttrInfoVo getInfoWithAttrId(Long attrId) {
        AttrEntity attrEntity = this.getOne(new QueryWrapper<AttrEntity>().eq("attr_id", attrId));
        AttrInfoVo attrInfoVo = new AttrInfoVo();
        BeanUtil.copyProperties(attrEntity, attrInfoVo);
        List<Long> path = new ArrayList<>();
        Long catelogId = attrEntity.getCatelogId();
        List<Long> coverPath = recursionFindPath(catelogId, path);
        Collections.reverse(coverPath);
        Long[] longs = new Long[coverPath.size()];
        Long[] pathArray = coverPath.toArray(longs);
        attrInfoVo.setCatelogPath(pathArray);
        Integer type = attrEntity.getAttrType();
        if(type==1) {
            AttrAttrgroupRelationEntity selectedOne = attrAttrgroupRelationDao.selectOne(new
                    QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrId));
            if(selectedOne==null){
                attrInfoVo.setAttrGroupId(null);
            }else {
                Long attrGroupId = selectedOne.getAttrGroupId();
                attrInfoVo.setAttrGroupId(attrGroupId);
            }
        }
        return attrInfoVo;
    }

    @Transactional
    @Override
    public void updateAttr(AttrVo attr) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtil.copyProperties(attr, attrEntity);
        // 保存自己数据
        this.updateById(attrEntity);
        // 更新其他连表数据
        // 1 获取attid
        Long attrId = attrEntity.getAttrId();
        Long attrGroupId = attr.getAttrGroupId();
        // 2 根据id 获取最新的attr 与relation
        if(attr.getAttrType()==1) {
            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = attrAttrgroupRelationDao.selectOne(new
                    QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrId));
            if(attrAttrgroupRelationEntity!=null){
                // 3 根据关系表获取(设置)分组id
                attrAttrgroupRelationEntity.setAttrGroupId(attrGroupId);
                // 4 保存关联表
                attrAttrgroupRelationDao.updateById(attrAttrgroupRelationEntity);
            } else {
                AttrAttrgroupRelationEntity entity = new AttrAttrgroupRelationEntity();
                entity.setAttrGroupId(attrGroupId);
                entity.setAttrId(attrId);
                attrAttrgroupRelationDao.insert(entity);
            }

        }
    }

    @Override
    public PageUtils getSaleListInfoBycateLogId(Long catelogId, Map<String, Object> params) {
        String key = (String) params.get("key");
        QueryWrapper<AttrEntity> attrEntityQueryWrapper = new QueryWrapper<>();
        if (catelogId != 0) {
            attrEntityQueryWrapper.eq("catelog_id", catelogId);
        }
        if (StrUtil.isNotBlank(key)) {
            // 关键字不为空的情况
            attrEntityQueryWrapper.and((item) -> {
                item.eq("attr_id", key).or().like("attr_name", key);
            });
        }
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                attrEntityQueryWrapper
        );
        List<AttrEntity> records = page.getRecords();
        List<AttrEntityVo> collect = records.stream().map((item) -> {
            AttrEntityVo attrEntityVo = new AttrEntityVo();
            BeanUtil.copyProperties(item, attrEntityVo);
            Long catelogId1 = item.getCatelogId();
            CategoryEntity categoryEntity = categoryDao.selectOne(new QueryWrapper<CategoryEntity>().eq("cat_id", catelogId1));
            attrEntityVo.setCatelogName(categoryEntity.getName());
            Long attrId = item.getAttrId();
            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = attrAttrgroupRelationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrId));
            Long attrGroupId = attrAttrgroupRelationEntity.getAttrGroupId();
            AttrGroupEntity attrGroupEntity = attrGroupDao.selectOne(new QueryWrapper<AttrGroupEntity>().eq("attr_group_id", attrGroupId));
            attrEntityVo.setGroupName(attrGroupEntity.getAttrGroupName());
            return attrEntityVo;
        }).collect(Collectors.toList());
        Page<AttrEntityVo> attrEntityVoPage = new Page<>();
        BeanUtil.copyProperties(page, attrEntityVoPage, "records");
        attrEntityVoPage.setRecords(collect);
        return new PageUtils(attrEntityVoPage);


    }

    @Override
    public List<Long> seletAttrIds(List<Long> allAttrIds) {

        return  baseMapper.seletValueIds(allAttrIds);
    }

    private List<Long> recursionFindPath(Long catelogId, List<Long> root) {
        CategoryEntity categoryEntity = categoryDao.selectOne(new QueryWrapper<CategoryEntity>().eq(
                "cat_id", catelogId
        ));
        Long parentCid = categoryEntity.getParentCid();
        root.add(categoryEntity.getCatId());
        if (parentCid != 0) {
            recursionFindPath(parentCid, root);
        }
        return root;
    }

}